import {
  SET_TOKEN,
  SET_REFRESH_TOKEN,
  SET_USER_INFO
} from '../types'

import Vue from 'vue'
import {
  phoneLogin,
  logout,
  refreshToken,
  logoff,
  getUserInfo
} from '@/api/auth'

export default {
  state: {
    token: '',
    refreshToken: '',
    userInfo: null
  },
  mutations: {
    [SET_TOKEN](state, token) {
      state.token = token;
    },
    [SET_REFRESH_TOKEN](state, refreshToken) {
      state.refreshToken = refreshToken;
    },
    [SET_USER_INFO](state, userInfo) {
      state.userInfo = userInfo;
    },
  },
  actions: {
    // 登录
    async authLogin({ commit, dispatch }, { mobile, code }) {
      Vue.prototype.$loading();
      const { data } = await phoneLogin({
        account: mobile,
        code,
      });
      Vue.prototype.$loading.close();
      if (!data) return;
      Vue.prototype.$navigateBack();
      const { accessToken, refreshToken, user } = data;
      commit('SET_TOKEN', accessToken)
      commit('SET_REFRESH_TOKEN', refreshToken)
      commit('SET_USER_INFO', user)
      dispatch("getAddress");
    },
    // 退出登录
    async logout({ dispatch }) {
      Vue.prototype.$loading();
      const { code } = await logout();
      Vue.prototype.$loading.close();
      if (code !== 200) return;
      Vue.prototype.$navigateBack();
      dispatch('clearUserInfo');
    },
    // 清除缓存用户信息
    clearUserInfo({ commit, dispatch }) {
      commit('SET_TOKEN', '');
      commit('SET_REFRESH_TOKEN', '');
      commit('SET_USER_INFO', null);
      commit('SET_DEFAULT_ADDRESS', null)
      commit('SET_CURRENT_ADDRESS', null)
      dispatch('getLocation')
    },
    // 注销
    async logoff({ dispatch }) {
      Vue.prototype.$loading();
      const { code } = await logoff();
      Vue.prototype.$loading.close();
      if (code !== 200) return;
      Vue.prototype.$navigateBack();
      dispatch('clearUserInfo');
    },
    // 刷新token
    async refreshToken({ getters, commit }) {
      if (getters.refreshToken) {
        const { data } = await refreshToken({ refreshToken: getters.refreshToken })
        if (!data) return 0
        commit('SET_TOKEN', data.accessToken);
        commit('SET_REFRESH_TOKEN', data.refreshToken);
        return 200
      }
      Vue.prototype.$checkLogin()
    },
    // 获取用户信息
    async getUserInfo({ commit }) {
      const { data } = await getUserInfo()
      if (data) commit('SET_USER_INFO', data)
    }
  }
};